package utils.http;


import okhttp3.*;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author muyl
 */
public final class OKHttpUtils {

    private static       OKHttpUtils  sInstance;
    private static final OkHttpClient mOkHttpClient   = new OkHttpClient();
    private static final MediaType    MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType    MEDIA_TYPE_TEXT = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");


    private OKHttpUtils() {
        /**
         * 设置连接超时时间为40s
         */
        mOkHttpClient.newBuilder().connectTimeout(40, TimeUnit.SECONDS);
        /**
         * 读取超时时间
         */
        mOkHttpClient.newBuilder().readTimeout(60, TimeUnit.SECONDS);
        /**
         * 写入超时时间
         */
        mOkHttpClient.newBuilder().writeTimeout(60, TimeUnit.SECONDS);

    }

    /**
     * 单例模式
     *
     * @return
     */
    public static OKHttpUtils instance() {
        if (sInstance == null) {
            synchronized (OKHttpUtils.class) {
                if (sInstance == null) {
                    sInstance = new OKHttpUtils();
                }
            }
        }
        return sInstance;
    }

    /**
     * 这是一个get请求拼接请求路径的方法
     *
     * @param requestPacket 请求参数
     * @return 请求uri
     */
    private static String appendUrl(RequestPacket requestPacket) {
        return requestPacket.url + "?" + appendArguments(requestPacket);
    }

    /**
     * 这是一个拼接get请求请求参数的方法
     *
     * @param requestPacket 请求参数
     * @return 处理url
     */
    private static String appendArguments(RequestPacket requestPacket) {
        StringBuilder argument = new StringBuilder();
        for (String key : requestPacket.arguments.keySet()) {
            if (requestPacket.getArgument(key) != null) {
                if ("".equals(argument.toString())) {
                    argument = new StringBuilder(key + "=" + requestPacket.getArgument(key));
                } else {
                    argument.append("&").append(key).append("=").append(requestPacket.getArgument(key));
                }
            }
        }
        return argument.toString();
    }

    /**
     * 这是一个拼接get请求请求参数的方法
     *
     * @param paramMap 请求参数
     * @return 处理url
     */
    private static String appendArguments(Map<String,Object> paramMap) {
        StringBuilder argument = new StringBuilder();
        Iterator<Map.Entry<String, Object>> iterator = paramMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            argument.append(entry.getKey()).append("=").append(entry.getValue());
            if (iterator.hasNext()) {
                argument.append("&");
            }
        }
        return argument.toString();
    }


    public static boolean downloadSmallFile(final String uri, final String filePath, final String filename) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(uri).build();

        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                return false;
            }

            ResponseBody body = response.body();
            BufferedSource source = body.source();
            String responseFileName = getHeaderFileName(response);
            File file = null;
            if (StringUtils.isEmpty(responseFileName)) {
                file = new File(filePath + filename);
            } else {
                file = new File(filePath + responseFileName);
            }
            BufferedSink sink = Okio.buffer(Okio.sink(file));
            sink.writeAll(source);
            sink.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * Get方法调用
     *
     * @param url 请求Url
     * @return 调用结果
     */
    public String sendByGetUrl(String url) {
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = mOkHttpClient.newCall(request).execute();
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 异步Get方式调用
     *
     * @param url      请求URl
     * @param callback 回调
     */
    public void asynGet(String url, Callback callback) {
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * post方式调用
     *
     * @param url  请求URL
     * @param json 调用参数
     * @return 调用结果
     */
    public String sendByPostJson(String url, String json) {
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = null;
        try {
            response = mOkHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendByPostMap(String url, Map<String, Object> params) {
        OkHttpClient client = new OkHttpClient();
        String arguments = appendArguments(params);

        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, arguments);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 异步调用Post方法
     *
     * @param url      请求参数
     * @param json     请求字符串
     * @param callback 回调方法
     */
    public void asynPost(String url, String json, Callback callback) {
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, json);
        Request request = new Request.Builder()
                .method("POST", requestBody)
                .url(url)
                .build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }


    /**
     * 这是一个下载文件的方法
     *
     * @param filepath 文件路径
     * @param filename 文件名字
     * @param listener 回调监听
     */
    public void donwloadFile(final String filepath, RequestPacket requestPacket, final String filename, final ResponseListener listener) {
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(appendUrl(requestPacket)).build();
        //发送异步请求
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onfailure();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() != 200) {
                    return;
                }
                String responseFileName = getHeaderFileName(response);
                File file = null;
                if (StringUtils.isEmpty(responseFileName)) {
                    file = new File(filepath + filename);
                } else {
                    file = new File(filepath + responseFileName);
                }
                assert response.body() != null;
                try (InputStream inputStream = response.body().byteStream();
                     FileOutputStream outputStream = new FileOutputStream(file)) {
                    long total = response.body().contentLength();
                    long sum = 0;
                    //将返回结果转化为流，并写入文件
                    int len;
                    byte[] buf = new byte[2048];
                    while ((len = inputStream.read(buf)) != -1) {
                        outputStream.write(buf, 0, len);
                        sum += len;
                        listener.onProcess(sum, total, false);
                    }
                    outputStream.flush();
                }
                listener.onSuccess(file);
            }

        });
    }

    /**
     * 解析文件头 Content-Disposition:attachment;filename=FileName.txt Content-Disposition: attachment;
     * filename*="UTF-8''%E6%9B%BF%E6%8D%A2%E5%AE%9E%E9%AA%8C%E6%8A%A5%E5%91%8A.pdf"
     */
    private static String getHeaderFileName(Response response) {
        String dispositionHeader = response.header("Content-Disposition");
        dispositionHeader.replace("attachment;filename=", "");
        dispositionHeader.replace("filename*=utf-8", "");
        String[] strings = dispositionHeader.split("; ");
        if (strings.length > 1) {
            dispositionHeader = strings[1].replace("filename=", "");
            dispositionHeader = dispositionHeader.replace("\"", "");
            return dispositionHeader;
        }
        return "";
    }


    public static void main(String[] args) {
        downloadSmallFile("https://codeload.github.com/alibaba/Sentinel/zip/master"
                , "/Users/muyl/logs/", "b.jpg");
    }
}
